<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Business;

use App\Constants\Constants;
use App\Dao\AreaDao;
use App\Dao\BusinessDao;
use App\Dao\BusinessIndustryDao;
use App\Dao\LocationDao;
use App\Dao\UserDao;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;
use function AlibabaCloud\Client\json;

/**
 * 商家服务
 *
 * @author 李想(928674263@qq.com)
 * @package App\Service\Business
 */

class BusinessService extends Service
{
    /**
     * @Inject
     * @var BusinessDao
     */
    public $dao;

    /**
     * @Inject
     * @var AreaDao
     */
    public $area_dao;

    /**
     * @Inject
     * @var UserDao
     */
    public $user_dao;

    /**
     * @Inject
     * @var BusinessIndustryDao
     */
    public $business_industry_dao;

    /**
     * @Inject
     * @var LocationDao
     */
    public $location_dao;

    /**
     * 获取不通过的商家信息
     */
    public function getFailBusiness()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        if( empty( $user ) ) {
            $this->error('BUSINESS.NOT_EXIST');
        }

        $business = $user->business;


        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if (empty($business) || (empty($business->status) && $business->status == 1)) {
            $this->error('BUSINESS.NOT_Fail');
        }

        $parent = $this->user_dao->first($business['parent_id'],false);
        $business['type'] = '';
        //返回商家入驻方式 1：全店打折 2：优惠券 3现金抵扣券
        if ( $business->enable_full_discount == 1 ) {
            $business['type'] = 3;
        } else if ( $business->enable_coupon == 1 ) {
            $business['type'] = 1;
        } else if ( $business->enable_voucher == 1 ) {
            $business['type'] = 2;
        } else {
            $business['type'] = '';
        }
        $user['industry_name'] = $this->business_industry_dao->getBusinessIndustryById($business->industry_id);

        $user['business']['parent_identity_code'] = $parent['identity_code'];

        $province = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['province_id']
        ] );

        $city = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['city_id']
        ] );

        $district = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['district_id']
        ] );
        $user['business']['province_pid'] = $province['pid'];
        $user['business']['city_pid'] = $city['pid'];
        $user['business']['district_pid'] = $district['pid'];
        //返回用户所有信息
        return $user['business'];
    }

    /**
     * 获取登录商家状态
     *
     * @return mixed
     */
    public function getBusinessStatus()
    {
        $user_id = uid();

        $business = $this->dao->first(['user_id' => $user_id]);

        return $business ? $business->status : false;
    }

    /**
     * 商家认证
     *
     * @param array $data 认证资料
     */
    public function cert(array $data)
    {
        $user_id = uid();

        $business = $this->dao->find([
            ['user_id' => $user_id],
        ]);

        //获取验证码和校验验证码
        // 判断验证码是否输入正确

        $record = $this->redis->get(Constants::CODE_REDIS_PREFIX . $data['tel']);
        $record = !$record ?: json_decode($record, true);
        if (!$record || !isset($record['code']) || (string)$record['code'] !== $data['code']) {
            $this->error('COMMON.CODE_ERROR');
        }
        $this->redis->del(Constants::CODE_REDIS_PREFIX . $data['tel']);//删除验证码

//         之前认证过，并且未通过审核的商家才能继续认证
        if ($business && $business->status !== 3) {
            $this->error('BUSINESS.ALREADY_AUTH');
        }
        
        $province = $this->location_dao->getLocationByPid( [
            'pid' => $data['province_id']
        ] );

        $city = $this->location_dao->getLocationByPid( [
            'pid' => $data['city_id']
        ] );

        $district = $this->location_dao->getLocationByPid( [
            'pid' => $data['district_id']
        ] );


        // 下级地区不属于上级地区返回错误
        if ($province->pid !== $city->level || $city->pid !== $district->level) {
            $this->error('BUSINESS.LOCATION_ERROR');
        }

        //获取上级id，上级必须是渠道商
        $group = $this->user_dao::USER_CHANNEL_BUSINESS;
        $parent_id = $this->user_dao->getUserByIdentityCode($data['identity_code'],'id',$group);
        $data['parent_id'] = $parent_id['id'];

        //判别入驻方式
        switch ($data['settled_type']) {
            case 3:
                $data['enable_full_discount'] = 1;//全店打折
                break;
            case 1:
                $data['enable_coupon'] = 1;//优惠券
                break;
            case 2:
                $data['enable_voucher'] = 1;//现金抵扣券
                break;
            default :
                break;
        }

        // 定义新增/更新数据
        $save_data = [
            'user_id' => $user_id,//用户id
            //---------------商家实名--------------------------------------
            'business_name' => $data['business_name'],//商家真实姓名
            'business_card_id' => $data['business_card_id'],//商家的身份证号码
            'business_bank_id' => $data['business_bank_id'],//商家关联的银行卡id（非银行卡号）
            'business_idcard_positive' => $data['business_idcard_positive'],//商家身份证正面
            'business_idcard_negative' => $data['business_idcard_negative'],//商家身份证反面


            //----------------店铺信息------------------------------------------------------------
            'company_name' => $data['company_name'],//公司全称
            'logo' => $data['logo'],//店铺logo
            'phone' => $data['phone'],//店铺营业电话
            'name' => $data['company_name'],//公司全称
            'description' => $data['description'],//店铺介绍
            'legal_name' => $data['legal_name'],//公司法人
            'industry_id' => $data['industry_id'],//行业类别
            'province_id' => $province->pid,//省份id
            'province' => $province->name,//省份名称
            'city_id' => $city->pid,//城市id
            'city' => $city->name,//城市名称
            'district_id' => $district->pid,//县/区id
            'district' => $district->name,//县、区名称
            'address' => $data['address'],//详细地址
            'forenoon_hours' => $data['forenoon_hours'],//上午营业时间
            'afternoon_hours' => $data['afternoon_hours'],//下午营业时间
            'science' => json_encode($data['science']),//详细地址

            //-----------------入驻方式---------------------------------------------------------------------
            'enable_full_discount' => isset($data['enable_full_discount']) ? 1 : 0,
            'enable_coupon' => isset($data['enable_coupon']) ? 1 : 0,
            'enable_voucher' => isset($data['enable_voucher']) ? 1 : 0,
            //-----------------营业执照------------------------------------------------------------------------
            'company_license_pic' => $data['company_license_pic'],
            //------------------其他有效资质-------------------------------------------
            'other_certificates' => json_encode($data['other_certificates']),
            'tel' => $data['tel'], //电话
            'status' => 2,//审核状态
            //-----------经纬度-----------------
            'longitude' => $data['longitude'],//商家经度
            'latitude' => $data['latitude'],//商家纬度
            'location' => $data['location'],//定位时的位置
            'parent_id' => $data['parent_id'],//上级id
        ];

        $business_cert = $business ? $this->dao->update([
            ['user_id' => $user_id]
        ], $save_data) : $this->dao->create($save_data);

        !$business_cert && $this->error();
    }

    /**
     * 获取商家加盟方式
     *
     * @return array
     */
    public function getJoiningWay()
    {
        $user = UserJwtInstance::instance()->build()->getUser();
        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }
        //判断商家的入驻方式，返回商家入驻方式 3：全店入驻，1：优惠券，2：现金抵用
        $type = '';
        if ($business->enable_full_discount == 1) {
            $type = 3;
        }
        if ($business->enable_coupon == 1) {
            $type = 1;
        }
        if ($business->enable_voucher == 1) {
            $type = 2;
        }
        return [
            'type'=>$type
        ];

    }

    /**
     * 更改商家加盟方式
     *
     * @param array $data
     */
    public function changeJoiningWay(array $data)
    {
        $user = UserJwtInstance::instance()->build()->getUser();
        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }

        $result = $this->dao->update($business->id, [
            'enable_full_discount' => $data['enable_full_discount'] ?? 0,
            // 没有启用全店打折时 全店打折比例设为0
            'full_discount_rate' => $data['enable_full_discount'] === 1 ? $business->full_discount_rate : 0,
            'enable_coupon' => $data['enable_coupon'] ?? 0,
            'enable_voucher' => $data['enable_voucher'] ?? 0,
        ]);

        !$result && $this->error();
    }

    /**
     * 获取商家全店打折比例
     *
     * @return float
     */
    public function getFullDiscountRate()
    {
        $user = UserJwtInstance::instance()->build()->getUser();
        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }

        // 商家是否选择全店打折加盟
        if ($business->enable_full_discount === 0) {
            $this->error('BUSINESS.FULL_DISCOUNT_ERROR');
        }

        return $business->full_discount_rate;
    }

    /**
     * 更改全店打折比例
     *
     * @param array $data
     */
    public function changeFullDiscountRate(array $data)
    {
        $user = UserJwtInstance::instance()->build()->getUser();
        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }

        // 商家是否选择全店打折加盟
        if ($business->enable_full_discount === 0) {
            $this->error('BUSINESS.FULL_DISCOUNT_ERROR');
        }

        $result = $this->dao->update($business->id, [
            'full_discount_rate' => $data['full_discount_rate'] ?? 0,
        ]);

        !$result && $this->error();
    }

    /**
     * 获取商家信息
     * 
     * @return mixed
     */
    public function getInfo()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        if( empty( $user ) ) {
            $this->error('BUSINESS.NOT_EXIST');
        }

        $business = $user->business;
        $business['type'] = '';

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if (empty($business) || (empty($business->status) && $business->status != 1)) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }
        //返回商家入驻方式 1：全店打折 2：优惠券 3现金抵扣券
        if ( $business->enable_full_discount == 1 ) {
            $business['type'] = 3;
        } else if ( $business->enable_coupon == 1 ) {
            $business['type'] = 1;
        } else if ( $business->enable_voucher == 1 ) {
            $business['type'] = 2;
        } else {
            $business['type'] = '';
        }

        $province = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['province_id']
        ] );

        $city = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['city_id']
        ] );

        $district = $this->location_dao->getLocationByPid( [
            'id' => $user['business']['district_id']
        ] );
        $user['business']['province_pid'] = $province['pid'];
        $user['business']['city_pid'] = $city['pid'];
        $user['business']['district_pid'] = $district['pid'];
        $user['industry_name'] = $this->business_industry_dao->getBusinessIndustryById($business->industry_id);
        //返回用户所有信息
        return $user;
    }

    /**
     * 修改商家信息
     *
     * @param array $data
     * @throws
     */
    public function changeInfo(array $data)
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        $business = $user->business;

        !$business && $this->error('BUSINESS.NOT_EXIST');

        // 商家是否通过审核
        if ($business->status != 1) {
            $this->error('BUSINESS.NOT_PASS_CERT');
        }

//        // 获取地区
        if ( isset($data['province_id']) ) {
            $province = $this->location_dao->getLocationByPid( [
                'pid' => $data['province_id']
            ] );


            $city = $this->location_dao->getLocationByPid( [
                'pid' => $data['city_id']
            ] );

            $district = $this->location_dao->getLocationByPid( [
                'pid' => $data['district_id']
            ] );

            // 下级地区不属于上级地区返回错误
            if ($province->pid !== $city->level || $city->pid !== $district->level) {
                $this->error('BUSINESS.LOCATION_ERROR');
            }

            $params['province'] = $province['name'];
            $params['city'] = $city['name'];
            $params['district'] = $district['name'];
            $params['province_id'] = $district->id;
            $params['city_id'] = $district->id;
            $params['district_id'] = $district->id;
        }

        if ( isset($data['identity_code']) ) {
           $parent_id = $this->user_dao->getUserByIdentityCode($data['identity_code'],'id');
           $data['parent_id'] = $parent_id['parent_id'];
        }

        if (isset($data['science'])) {
            $data['science'] = json_encode( $data['science'] );
        }

        if (isset($data['logo'])) {
            $data['logo'] = $data['logo'];
        }

        if (isset($data['tag'])) {
            $data['tag'] = json_encode($data['tag']);
        }

        $field = [
            'id',
            'name',
            'industry_id',
            'description',
            'science',
            'forenoon_hours',
            'afternoon_hours',
            'hours_describe',
            'longitude',
            'latitude',
            'tel',
            'province_id',
            'city_id',
            'district_id',
            'province',
            'city',
            'district',
            'enable_voucher',
            'enable_coupon',
            'enable_full_discount',
            'business_cover',
            'logo',
            'tag',
            'parent_id',
        ];

        $field_all = array_intersect(array_keys($data),$field );

        foreach ($field_all as $field) {
            $params[$field] = $data[$field];
        }

        $update = $this->dao->update($business->id,$params);

        !$update && $this->error();

    }
}